package com.clz.appdesign.myapp.view;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.Rect;
import android.graphics.RectF;
import android.graphics.Region;
import android.graphics.RegionIterator;
import android.support.annotation.Nullable;
import android.util.AttributeSet;
import android.view.View;

/**
 * @author chenliangzhi
 * @date 2018/5/22
 * @describe 画区域
 */

public class MyRegionView extends View {
    public MyRegionView(Context context) {
        super(context);
    }

    public MyRegionView(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
    }

    public MyRegionView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        //初始化画笔
        Paint paint = new Paint();
        paint.setColor(Color.RED);
        paint.setStyle(Paint.Style.FILL);
        paint.setStrokeWidth(2);
        Region region = new Region(10, 10, 100, 100);
        //区域替换
        region.set(100, 100, 200, 200);
        //drawRegion(region, canvas, paint);

        //构造一个椭圆路径
        RectF rectf = new RectF(50, 50, 200, 500);
        Path ovalPath = new Path();
        ovalPath.addOval(rectf, Path.Direction.CCW);
        Region region2 = new Region();
        region2.setPath(ovalPath, new Region(50, 50, 200, 200));
        //drawRegion(region2,canvas,paint);

        /**
         * 假设用region1  去组合region2
         public enum Op {
         DIFFERENCE(0), //最终区域为region1 与 region2不同的区域
         INTERSECT(1), // 最终区域为region1 与 region2相交的区域
         UNION(2),      //最终区域为region1 与 region2组合一起的区域
         XOR(3),        //最终区域为region1 与 region2相交之外的区域
         REVERSE_DIFFERENCE(4), //最终区域为region2 与 region1不同的区域
         REPLACE(5); //最终区域为为region2的区域
         }
         */
        Rect rect1 = new Rect(50, 200, 400, 300);
        Rect rect2 = new Rect(100, 100, 200, 400);
        paint.setStyle(Paint.Style.STROKE);
        paint.setColor(Color.RED);
        paint.setStrokeWidth(2);
        canvas.drawRect(rect1,paint);
        canvas.drawRect(rect2,paint);
        Region region1=new Region(rect1);
        Region region3=new Region(rect2);
        //取两个区域的交集
        region1.op(region3, Region.Op.INTERSECT);
        paint.setColor(Color.GREEN);
        paint.setStyle(Paint.Style.FILL);
        drawRegion(region1,canvas,paint);
    }

    private void drawRegion(Region region, Canvas canvas, Paint paint) {
        RegionIterator regionIterator = new RegionIterator(region);
        Rect rect = new Rect();
        while (regionIterator.next(rect)) {
            canvas.drawRect(rect, paint);
        }
    }
}
